<template>
  <div class="main-content">
    <div class="search-container">
      <common-select
        :multiple="multiple"
        key-field="saleStatus"
        show-field="saleStatusName"
        val-field="saleStatus"
        :list="premisesStatusEnum"
        placeholder="全部楼盘状态"
        v-model="premisesStatus"
      />
      <common-select
        :filterable="filterable"
        :multiple="multiple"
        key-field="id"
        show-field="name"
        val-field="id"
        :list="premiseList"
        placeholder="全部楼盘"
        v-model="params.premisesIds"
      />
      <label style="font-size: 18px;">报备时间：</label>
      <el-date-picker
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="统计时间"
        end-placeholder
      >
        <!--									:value-format="FORMAT"-->
      </el-date-picker>
      <div style="margin-top: 10px; text-align: center;">
        <button type="button" class="btn" @click="search()">查询</button>
        <button
          v-if="userAuthResources.indexOf(resourcesList.menu_0007_0008_0001) >= 0"
          type="button"
          class="btn"
          v-on:click="exportData"
        >导出</button>
      </div>
    </div>
    <div id="myChart" :style="{ width: '100%', height: '450px' }"></div>
    <div class="qf-table-title">
      <span>到访与签约关系</span>
      <!-- <div class="qf-title-link" @click="open()">
        <img src="../../assets/images/help.svg" alt="头像" />
        如何录入多次到访
      </div> -->
    </div>
    <div class="table-container">
      <el-table
        class="recommend-report-table"
        type="index"
        label="排名"
        show-summary
        :data="tableData"
        :loading="loading"
        title="到访与签约关系"
      >
        <el-table-column
          prop="visitType"
          key="visitType"
          label="到访类型"
        >
        <template slot-scope="scope">
          {{scope.row.visitType}}
          <el-tag
            style="margin-left:5px"
            v-if="scope.row.signRateMax==='1'"
            color="#f87242"
            size="mini"
            effect="dark"
            type="warning">
            签约率最高
          </el-tag>
        </template>
        </el-table-column>
        <el-table-column
          v-for="item in columns"
          :prop="item.prop"
          :width="item.width"
          :key="item.prop"
          :label="item.label"
        ></el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import CommonSelect from "../../components/common/CommonSelect.vue";
import CommonTable from "../../components/common/CommonTable.vue";
import Echarts from "echarts";
import { Service, API, Utils } from "../../js/base";
const RECOMMEND_DIMENSION = "0";
const PREMISE_DIMENSION = "1";
export default {
  name: "visitReport",
  components: {
    CommonSelect,
    CommonTable
  },
  data() {
    return {
      FORMAT: "YYYY-MM-DD",
      date: [
        moment().startOf("month"), //.format(this.FORMAT),
        moment()
      ],
      dimension: {
        recommend: RECOMMEND_DIMENSION,
        premise: PREMISE_DIMENSION
      },
      TRUE: true,
      multiple: true,
      filterable: true,
      params: {
        endDate: "", // 统计结束日期
        premisesIds: [], //楼盘id集合
        startDate: "" //  开始日期
      },
      premiseList: [],
      recommendList: [],
      premisesStatus: "",

      baseColumns: [
        {
          prop: "visitCount",
          label: "到访数量"
        },
        {
          prop: "signCount",
          label: "签约成功数"
        },
        {
          prop: "signRate",
          label: "签约成功率"
        }
      ],
      columnsVisitCountData: [],
      columnsSignCountData: [],
      columns: [],
      premisesStatusEnum: [
        { saleStatus: 0, saleStatusName: "待售", saleStatusFlag: false },
        { saleStatus: 1, saleStatusName: "在售", saleStatusFlag: true },
        { saleStatus: 2, saleStatusName: "售罄", saleStatusFlag: false },
        { saleStatus: 3, saleStatusName: "下架", saleStatusFlag: false }
      ],
      resourcesList: {
        menu_0007_0008_0001: "menu_0007_0008_0001" //导出
      },
      userAuthResources: window.localStorage.getItem("userAuthResources"),
      tableData: [],
      dataTotal: 0,
      loading: false
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    // open() {
    //   this.$alert("这是一段内容", "如何录入多次到访", {
    //     confirmButtonText: "我知道了",
    //     center: true,
    //   });
    // },
    drawLine() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = Echarts.init(document.getElementById("myChart"));
      // 绘制图表
      myChart.setOption({
        title: { text: "" },
        tooltip: {},
        legend: {
          data: ["到访报备数", "签约报备数"],
          right: "4%"
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: ["首次到访", "2次到访", "3次到访", "3次以上到访"]
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "到访报备数",
            type: "bar",
            stack: "数据",
            color: "#FFCC00",
            label: {
              show: true,
              position: "inside"
            },
            barWidth: "80px",
            data: this.columnsVisitCountData
          },
          {
            name: "签约报备数",
            type: "bar",
            stack: "数据",
            color: "#EE803E",
            barWidth: "80px",
            label: {
              show: true,
              position: "inside"
            },
            data: this.columnsSignCountData
          }
        ]
      });
    },
    init() {
      this.getRecommendList();
      this.getPremiseList();
      this.getList();

      this.columns = [...this.baseColumns];
    },
    changeMenuSelect(val) {
      this.params.status = val;
    },
    /**
     * 查询
     */
    search() {
      this.getList();
    },
    /**
     * 导出数据
     */
    exportData() {
      var loadIndex = layer.load();
      let _this = this;
      let params = Utils.deepClone(this.params);
      params.userId = window.localStorage.getItem("1_userId");
      params.loginType = "1";
      params.startDate = params.startDate
        ? moment(params.startDate).format("YYYY-MM-DD")
        : "";
      params.endDate = params.endDate
        ? moment(params.endDate).format("YYYY-MM-DD")
        : "";

      let intervalDays = this.utils.intervalTime(params.startDate, params.endDate);
      if(intervalDays > 31){
        layer.close(loadIndex);
        layer.msg("单次最多获取31天的数据!");
        return false;
      }
      
      const api = API.DATA_CENTER.exportVisitState;
      let url =
        this.utilHelper.apiUrl +
        api +
        "?" +
        Utils.stringfiyParams(params, "params.");
      window.location.href = url;
      layer.close(loadIndex);
    },
    /**
     * 获取列表数据
     * @param params
     */
    getList(params = this.params) {
      var loadIndex = layer.load();
      let _this = this;
      _this.loading = true;
      params.startDate = params.startDate
        ? moment(params.startDate).format("YYYY-MM-DD")
        : "";
      params.endDate = params.endDate
        ? moment(params.endDate).format("YYYY-MM-DD")
        : "";

      let intervalDays = this.utils.intervalTime(params.startDate, params.endDate);
      if(intervalDays > 31){
        layer.close(loadIndex);
        layer.msg("单次最多获取31天的数据!");
        return false;
      }

      Service.DataCenter.getVisitStateList({ params, _this })
        .then(rsp => {
          layer.close(loadIndex);
          let columnsVisitCountData = [];
          let columnsSignCountData = [];
          if (rsp.length > 0) {
            rsp.map((val, i) => {
              columnsVisitCountData.push(val.visitCount);
              columnsSignCountData.push(val.signCount);
            });
          }
          _this.columnsVisitCountData = columnsVisitCountData;
          _this.columnsSignCountData = columnsSignCountData;
          this.drawLine();
          _this.tableData = rsp;
          _this.columnsVisitCountData = [];
          _this.loading = false;
        })
        .catch(error => {
          layer.close(loadIndex);
          _this.loading = false;
        });
    },
    /**
     * 获取楼盘列表
     */
    getPremiseList(val = "") {
      let premisesStatus = "";
      this.premiseList = [];
      if (val) {
        premisesStatus = val.join(",");
      }
      let params = {
        premisesStatus: premisesStatus
      };

      let _this = this;
      Service.Premise.getPremisesListByStatus({
        params,
        _this
      }).then(rsp => {
        this.premiseList = rsp.inPremisesList;
      });
    },
    /**
     * 获取推荐人列表
     */
    getRecommendList() {
      const _this = this;
      let params = {
        id: "1"
      };
      Service.Recommend.getChannelAllRecommendList({ params, _this }).then(
        rsp => {
          _this.recommendList = rsp.list;
        }
      );
    },
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.getList();
    }

    // sizeChange (val) {
    // 	this.params.pageSize = val
    // 	this.getList()
    // },
    /**
     * 翻页触发
     * @param val
     */
    // pageChange (val) {
    // 	console.log(val)
    // 	this.pagination.current = val.pageNo || this.pagination.current
    // 	this.params.pageSize = val.pageSize || this.params.pageSize
    // 	this.getList()
    // },
  },
  watch: {
    premisesStatus(val) {
      this.getPremiseList(val);
    },
    date: {
      handler(val) {
        let startDate = "";
        let endDate = "";
        if (val && Array.isArray(val)) {
          startDate = val[0];
          endDate = val[1];
        }
        if (this.params) {
          this.params.startDate = startDate;
          this.params.endDate = endDate;
        }
      },
      immediate: true,
      deep: true
    },
    "params.status": {
      handler(val) {
        if (val === RECOMMEND_DIMENSION) {
          this.columns = [...this.baseColumns];
        } else {
          this.columns = [...this.baseColumns];
        }
        this.getList();
      },
      immediate: true,
      deep: true
    }
  }
};
</script>
<style>
.recommend-report-table .el-table th {
  background-color: #f5f7fa;
}
</style>
<style scoped lang="less">
.search-container {
  padding: 20px 0;
  .filter-empty {
    padding: 0 10px;
  }
  .btn {
    background-color: #f87242;
    color: #fff;
  }
}
.qf-table-title {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  span {
    font-size: 18px;
    font-weight: 700;
    margin-right: 15px;
  }

  .qf-title-link {
    cursor: pointer;
    font-size: 14px;
    color: #f87242;
    img {
      width: 14px;
      vertical-align: text-top;
    }
  }
}
</style>
